package com.yf.openapi.interceptor;

import com.yf.ability.redis.service.RedisService;
import com.yf.base.api.api.ApiError;
import com.yf.base.api.exception.ServiceException;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;


@Component
@Log4j2
public class SignInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    public static final String ACCESS = "access";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();

        // 从参数获得值
        String token = request.getHeader(ACCESS);

        // 再尝试从参数中获取
        if(StringUtils.isBlank(token)){
            token = request.getParameter(ACCESS);
        }

        // 未携带access
        if(StringUtils.isBlank(token)){
            throw new ServiceException(MessageFormat.format("请求头或GET传入：{0}", ACCESS));
        }

        // 校验授权信息
        String access = redisService.getString(token);
        if(StringUtils.isBlank(access)){
            throw new ServiceException(ApiError.ERROR_20020001);
        }

        System.out.println("\n-------- LogInterception.preHandle --- ");
        System.out.println("Request URL: " + request.getRequestURL());
        System.out.println("Start Time: " + System.currentTimeMillis());
        request.setAttribute("startTime", startTime);
        return true;
    }
}
